package cn.baage.campus.config.security.handler;

import cn.baage.campus.enums.ExceptionType;
import cn.baage.campus.utils.ResultUtils;
import cn.baage.campus.utils.Result;
import com.alibaba.fastjson2.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



/**
 * @Description: 认证异常处理器
 * @Author: 八阿哥
 * @url: baage.cn
 * @Version: 1.0
 **/
@Component
public class RestUnauthorizedHandler implements AuthenticationEntryPoint
{
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException
    {
        ExceptionType authenticationError = ExceptionType.AUTHENTICATION_ERROR;
        Result<Object> result = Result.fail(authenticationError.getErrorCode(), authenticationError.getErrorMessage());
        String jsonString = JSON.toJSONString(result);
        ResultUtils.renderString(response, jsonString);
    }
}